<template>
	<view class="container">
		<view class="content">
			<!-- <view class="top">
				<text class="h2">宿舍用水量查询</text>
			</view> -->

			<form class="middle">
				<view class="form">
					<text class="form-field">宿舍门牌:</text>
					<input type="text" :value="data1.SS_MC" name="houseNumber" disabled />
				</view>
				<view class="form">
					<text class="form-field">冷水余额:</text>
					<input type="text" :value="data1.totalMoney" name="electricityLeft" disabled />
				</view>
				<view class="form">
					<text class="form-field">补贴水量:</text>
					<input type="text" :value="data1.subsidyread" name="subsidyAmount" disabled />
				</view>
				<view class="form">
					<text class="form-field">水表状态:</text>
					<input type="text" :value="getStatusText()" name="meterStatus" disabled />
				</view>
				<view>
					<!-- <navigator url="/waterElectric/chargeWater/chargeWater"> -->
					<button class="btn" @click="connectBluetooth">充值</button>
					<!-- </navigator> -->
				</view>
				<view>
					<button class="btn" @click="getSubsidy">补贴领取</button>
				</view>
				<!--  <view>
          <button class="btn" @click="getCharge">充值领取</button>
        </view> -->
			</form>

			<!-- <view class="readTime">
				<text>采集时间 2024年4月1日</text>
				<text>本系统采集记录存在延迟,具体情况以水表为准。</text>
			</view> -->
		</view>

		<view class="bottom">
			<text>仅在12栋宿舍展示</text>
			<!-- <text>请移步到服务中心充值</text> -->
		</view>
	</view>
</template>

<script>
	import {
		ajax
	} from "../../utils/request.js";
	export default {
		data() {
			return {
				data1: {},
				uuid: "22:34:50:15:15:D8", // 静态 UUID
				bluetoothName: "CXR202407250541", // 静态蓝牙名
				deviceInfo: null // 新增设备信息存储
			};
		},
		onShow() {
			this.fetchFormData();
		},
		methods: {
			// 连接蓝牙（修改后的方法）
			async connectBluetooth() {
				uni.showLoading({
					title: "正在连接蓝牙...",
					mask: true
				});

				try {
					// 1. 初始化蓝牙适配器
					await this.initBluetoothAdapter();

					// 2. 连接设备
					const deviceId = await this.getDeviceId();
					await this.createBLEConnection(deviceId);

					// 3. 获取设备服务信息
					const deviceData = await this.getBluetoothServices(deviceId);

					// 4. 存储到本地
					this.saveDeviceInfo(deviceData);

					uni.hideLoading();
					uni.showModal({
						title: "提示",
						content: "蓝牙连接成功！",
						showCancel: false
					});
					uni.navigateTo({
						url: '/waterElectric/chargeWater/chargeWater'
					});
				} catch (err) {
					uni.hideLoading();
					uni.showModal({
						title: "提示",
						content: `连接失败：${err.message}`,
						showCancel: false
					});
				}
			},
			// 初始化蓝牙适配器
			initBluetoothAdapter() {
				return new Promise((resolve, reject) => {
					uni.openBluetoothAdapter({
						success: resolve,
						fail: (err) => reject(new Error('请开启蓝牙功能'))
					});
				});
			},
			// 获取设备ID（兼容iOS/Android）
			async getDeviceId() {
				if (uni.getSystemInfoSync().platform === "ios") {
					return await this.getBluetoothDeviceIdByName(this.bluetoothName);
				} else {
					return this.uuid;
				}
			},

			// 修改getBluetoothServices方法（补充serviceId关联）
			async getBluetoothServices(deviceId) {
				const services = await this.getServices(deviceId);
				const serviceDetails = await Promise.all(
					services.map(async service => ({
						serviceId: service.uuid, // 确保serviceId正确传递
						characteristics: await this.getCharacteristics(deviceId, service.uuid).then(
							chars =>
							chars.map(c => ({
								...c,
								serviceId: service.uuid // 为每个特征值添加所属serviceId
							}))
						)
					}))
				);

				return {
					deviceId,
					deviceName: this.bluetoothName,
					uuid: this.uuid,
					services: serviceDetails
				};
			},
			// 获取服务列表
			getServices(deviceId) {
				return new Promise((resolve, reject) => {
					uni.getBLEDeviceServices({
						deviceId,
						success: res => resolve(res.services),
						fail: () => reject(new Error('获取服务列表失败'))
					});
				});
			},

			// 获取特征值
			getCharacteristics(deviceId, serviceId) {
				return new Promise((resolve, reject) => {
					uni.getBLEDeviceCharacteristics({
						deviceId,
						serviceId,
						success: res => resolve(res.characteristics.map(c => ({
							uuid: c.uuid,
							properties: this.parseProperties(c.properties)
						}))),
						fail: () => reject(new Error('获取特征值失败'))
					});
				});
			},

			// 修改parseProperties方法（中英文属性转换问题）
			parseProperties(properties) {
				const props = [];
				// 改为使用英文属性标识
				if (properties.read) props.push('read');
				if (properties.write) props.push('write');
				if (properties.writeNoResponse) props.push('writeNoResponse');
				if (properties.notify) props.push('notify');
				if (properties.indicate) props.push('indicate');
				return props;
			},

			// 存储设备信息（新增）
			saveDeviceInfo(deviceData) {
				const fullInfo = {
					deviceCode: deviceData.deviceId,
					deviceName: deviceData.deviceName,
					uuid: deviceData.uuid,
					services: deviceData.services.map(service => ({
						serviceId: service.serviceId,
						characteristics: service.characteristics
					}))
				};

				console.log('完整设备信息:', fullInfo);
				uni.setStorageSync('bluetoothDeviceInfo', fullInfo);
			},
			// 连接蓝牙设备
			connectBluetoothDevice(uuid, bluetoothName) {
				return new Promise((resolve, reject) => {
					// 初始化蓝牙适配器
					uni.openBluetoothAdapter({
						success: () => {
							console.log("蓝牙适配器初始化成功");

							// 判断设备类型
							if (uni.getSystemInfoSync().platform === "ios") {
								console.log("iOS 设备，通过蓝牙名查找 UUID");
								this.getBluetoothDeviceIdByName(bluetoothName)
									.then((deviceId) => {
										console.log("找到设备ID:", deviceId);
										this.createBLEConnection(deviceId)
											.then(() => resolve())
											.catch((err) => reject(err));
									})
									.catch((error) => {
										console.error("错误:", error.message);
										reject(error);
									});
							} else {
								console.log("Android 设备，直接使用 UUID 连接");
								this.createBLEConnection(uuid)
									.then(() => resolve())
									.catch((err) => reject(err));
							}
						},
						fail: (err) => {
							console.error("蓝牙适配器初始化失败", err);
							reject(new Error("蓝牙适配器初始化失败"));
						},
					});
				});
			},

			// 创建蓝牙连接
			createBLEConnection(deviceId) {
				return new Promise((resolve, reject) => {
					uni.createBLEConnection({
						deviceId,
						success: () => {
							console.log("蓝牙连接成功");
							this.deviceInfo = {
								deviceId
							}; // 存储设备ID
							resolve();
						},
						fail: (err) => reject(new Error('设备连接失败'))
					});
				});
			},

			getBluetoothDeviceIdByName(deviceName) {
				return new Promise((resolve, reject) => {
					// 开始蓝牙设备扫描
					uni.startBluetoothDevicesDiscovery({
						success: () => {
							console.log("蓝牙设备扫描开始");
							let retryCount = 0;
							const maxRetry = 5; // 最大重试次数

							const getDevices = () => {
								uni.getBluetoothDevices({
									success: (res) => {
										console.log("获取蓝牙设备列表成功", res.devices);
										// 遍历设备列表，寻找名称匹配的设备
										for (let i = 0; i < res.devices.length; i++) {
											console.log(res.devices[i]);
											console.log(deviceName);
											console.log(res.devices[i].name ==
												deviceName);
											if (res.devices[i].name == deviceName) {
												// 找到设备，停止扫描并返回设备ID
												uni.stopBluetoothDevicesDiscovery();
												console.log("找到设备:", res.devices[i]);
												resolve(res.devices[i].deviceId);
												return;
											}
										}
										// 如果未找到设备，继续扫描
										if (retryCount < maxRetry) {
											retryCount++;
											console.log(`未找到设备，重试次数: ${retryCount}`);
											setTimeout(getDevices, 1000);
										} else {
											uni.stopBluetoothDevicesDiscovery();
											reject(new Error("未找到指定名称的蓝牙设备"));
										}
									},
									fail: (err) => {
										// 获取设备列表失败，返回错误信息
										uni.stopBluetoothDevicesDiscovery();
										console.error("获取蓝牙设备列表失败:", err);
										reject(new Error("获取蓝牙设备列表失败：" + err.errMsg));
									},
								});
							};
							// 开始第一次获取设备
							getDevices();
						},
						fail: (err) => {
							// 启动设备扫描失败
							console.error("启动蓝牙设备扫描失败:", err);
							reject(new Error("启动蓝牙设备扫描失败：" + err.errMsg));
						},
					});
				});
			},

			fetchFormData() {
				ajax("/api/meter/querywatermeter", "POST", {
						ss_mc: uni.getStorageSync("userInfo").ss_mc,
					})
					.then((data) => {
						console.log("成功数据:", data);
						this.data1 = data.data.coldwatermeter;
						// console.log("数据有:", this.data1);
						// 在这里存储 data1 的值
						uni.setStorageSync("device", this.data1);
						this.bluetoothName = data.data.coldwatermeter.BluetoothName;
						this.uuid = data.data.coldwatermeter.UUID;
					})
					.catch((error) => {
						console.error("请求失败:", error);
					});
			},
			getStatusText() {
				if (this.data1 && 'state' in this.data1) {
					if (this.data1.state == 1) {
						return "正常";
					} else if (this.data1.state == 0) {
						return "停用";
					}
				} else {
					return "未知";
				}
			},
			getBluetoothAdapterState(url) {
				uni.getBluetoothAdapterState({
					success(res) {
						if (res.poweredOn) {
							// 蓝牙已开启
							console.log('蓝牙已开启，可以进行蓝牙操作');
							uni.navigateTo({
								url: url,
							});
						} else {
							// 蓝牙未开启，需要初始化
							console.log('蓝牙未开启，正在初始化...');
							uni.openBluetoothAdapter({
								success: () => {
									console.log('蓝牙初始化成功');
									uni.navigateTo({
										url: url,
									});
								},
								fail: (err) => {
									console.error('蓝牙初始化失败', err);
									// 处理失败的情况，例如提示用户手动开启蓝牙
									uni.showToast({
										title: '蓝牙初始化失败\n请开启蓝牙',
										icon: 'none'
									})
								}
							});
						}
					},
					fail: (err) => {
						console.log('获取蓝牙适配器状态失败', err);
						// 处理失败的情况，例如提示用户检查蓝牙功能是否可用
						uni.openBluetoothAdapter({
							success: () => {
								console.log('蓝牙初始化成功');
								uni.navigateTo({
									url: url,
								});
							},
							fail: (err) => {
								console.error('蓝牙初始化失败', err);
								// 处理失败的情况，例如提示用户手动开启蓝牙
								uni.showToast({
									title: '蓝牙初始化失败\n请开启蓝牙',
									icon: 'none'
								})
							}
						});
					}
				});
			},
			getSubsidy() {
				this.getBluetoothAdapterState("/waterElectric/waterSubsidy/waterSubsidy")
			},
			getCharge() {
				this.getBluetoothAdapterState("/waterElectric/waterRechargeReward/waterRechargeReward")
			},
		},
	};
</script>

<style>
	.container {
		height: 100%;
		min-height: 100vh;
		width: 100%;
		background: linear-gradient(to bottom right, #39a755, #2ba245);
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 18px;
	}


	.content {
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		flex: 1;
		width: 50%;
	}


	.top {
		display: flex;
		justify-content: center;
	}

	.h2 {
		margin: 0;
		font-size: 20px;
		color: #fff;
		font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
	}


	.middle {
		justify-content: center;
		display: flex;
		flex-direction: row;
		height: 30%;
		align-items: center;
	}


	.form-field {
		padding-left: 0.5rem;
		width: 10rem;
		display: flex;
		justify-content: center;
	}


	form input {
		border: none;
		border-radius: 5px;
		height: 30px;
		line-height: 30px;
		text-align: center;
	}


	.form {
		height: 30px;
		line-height: 30px;
		margin: 10% auto;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		border-radius: 5px;
	}

	input:focus {
		outline: none;
	}



	.btn {
		height: 40px;
		background-color: rgba(43, 162, 69, 1.0);
		color: #fff;
		font-size: large;
		box-shadow: none;
		border-color: transparent;
		margin-bottom: 20px;
		/* 阴影 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
	}


	.readTime {
		color: #fff;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 18px;
	}


	.readTime text {
		text-align: center;
		font-size: 18px;
	}


	.bottom {
		color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		font-size: smaller;
		font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
		margin-bottom: 200px;
	}
</style>